package com.teacher.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teacher.common.CommonResult;
import com.teacher.mapper.TermMapper;
import com.teacher.pojo.dto.term.TermAddDto;
import com.teacher.pojo.dto.term.TermUpdateDto;
import com.teacher.pojo.entity.BaseEntity;
import com.teacher.pojo.entity.Term;
import com.teacher.service.ITermService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zfm
 * @since 2021-07-02
 */
@Service
public class TermServiceImpl extends ServiceImpl<TermMapper, Term> implements ITermService {

    /**
     * 添加学期
     *
     * @param dto
     * @return
     */
    @Override
    public CommonResult<String> add(TermAddDto dto) {
        Term term = new Term();
        BeanUtils.copyProperties(dto, term);
        if (this.save(term)) {
            return CommonResult.success("添加成功");
        }
        return CommonResult.failed("添加失败");
    }

    /**
     * 更改默认学期
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> updateInfo(TermUpdateDto dto) {

        if (!dto.getIsCurrent()) {
            if (this.count(new QueryWrapper<Term>().lambda()
                    .eq(BaseEntity::getId, dto.getId())
                    .eq(Term::getIsCurrent, true)) == 1) {
                return CommonResult.failed("必须要有一个当前学期");
            }
        }

        if (dto.getIsCurrent()) {
            this.update(new UpdateWrapper<Term>().lambda().set(Term::getIsCurrent, false));
        }
        Term term = new Term();
        BeanUtils.copyProperties(dto, term);
        this.updateById(term);
        return CommonResult.success("更新成功");
    }
}
